﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>03_ClickPoint</title>
    <link href="css/common.css" rel="stylesheet" />
</head>
<body>
    <canvas id="mycanvas"></canvas>
    <script id="shader-vs" type="x-shader/x-vertex">
        attribute vec4 aPosition;

        void main() {
        gl_Position = aPosition;
        gl_PointSize = 10.0;
        }
    </script>
    <script id="shader-fs" type="x-shader/x-fragment">
        void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
    </script>
    <script>
        var canvas = document.getElementById('mycanvas');
        canvas.width = canvas.clientWidth;
        canvas.height = canvas.clientHeight;

        var gl = canvas.getContext('webgl');

        var vertexShader = gl.createShader(gl.VERTEX_SHADER);
        gl.shaderSource(vertexShader, document.getElementById('shader-vs').innerHTML);
        gl.compileShader(vertexShader);

        var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(fragmentShader, document.getElementById('shader-fs').innerHTML);
        gl.compileShader(fragmentShader);

        var shaderProgram = gl.createProgram();
        gl.attachShader(shaderProgram, vertexShader);
        gl.attachShader(shaderProgram, fragmentShader);
        gl.linkProgram(shaderProgram);
        gl.useProgram(shaderProgram);

        var aPosition = gl.getAttribLocation(shaderProgram, 'aPosition');

        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);

        var points = [];
        canvas.onmousedown = function (e) {
            gl.clear(gl.COLOR_BUFFER_BIT);
            var x = (e.x / canvas.width - 0.5) * 2;
            var y = -(e.y / canvas.height - 0.5) * 2;
            points.push([x, y]);

            for (var i = 0; i < points.length; i++) {
                gl.vertexAttrib3f(aPosition, points[i][0], points[i][1], 0.0);
                gl.drawArrays(gl.POINTS, 0, 1);
            }
        }
    </script>
</body>
</html>
